package com.smooware.icms.fragment.sync;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;

import com.smooware.icms.InControllApp;
import com.smooware.icms.R;
import com.smooware.icms.service.AuthorizationServiceBinder;
import com.smooware.icms.service.ICMSAuthorizationService;

public class AuthorizationFragment extends Fragment {

	protected static final String TAG = AuthorizationFragment.class
			.getSimpleName();

	private AuthorizationServiceBinder service;

	private Context context;

	private boolean isServiceWorking = false;

	public AuthorizationFragment() {
	}

	@Override
	public View onCreateView(final LayoutInflater inflater,
			final ViewGroup container, final Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.login_fragment, container, false);

		view.findViewById(R.id.button_login).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(final View v) {
						service.startAuthorizationProcess();
					}
				});

		if (savedInstanceState != null) {
			restoreState(savedInstanceState);
		}

		return view;
	}

	@Override
	public void onActivityCreated(final Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

		context = getActivity();

		performAuthorizationCheck();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();

		unbindAuthorizationService();
	}

	@Override
	public void onSaveInstanceState(final Bundle outState) {
		outState.putBoolean("whatever", isServiceWorking);

		super.onSaveInstanceState(outState);

		Log.d(TAG, "save state");
	}

	/**
	 * Restores fragment state from {@link Bundle}.
	 * 
	 * @param savedInstanceState
	 *            {@link Bundle} to restore state from.
	 */
	private void restoreState(final Bundle savedInstanceState) {
		isServiceWorking = savedInstanceState.getBoolean("whatever");

		Log.d(TAG, "isServiceWorking " + isServiceWorking);
	}

	/**
	 * Checks if user is allready authorized. If he's not start authorization
	 * process.
	 */
	private void performAuthorizationCheck() {
		final InControllApp application = (InControllApp) context
				.getApplicationContext();

		if (!application.getICMSSecurityManager().isAuthorized()) {
			Log.d(TAG, "login service needs to be started");

			bindAuthorizationService();
		} else {

		}
	}

	/**
	 * Binds to service for performing authorization and synchronization.
	 */
	private void bindAuthorizationService() {
		Intent serviceIntent = new Intent(context,
				ICMSAuthorizationService.class);
		context.bindService(serviceIntent, serviceConnection,
				Context.BIND_AUTO_CREATE);

		isServiceWorking = true;
	}

	/**
	 * Check if this fragment is bounded to service and if it is unbinds it.
	 */
	private void unbindAuthorizationService() {
		if (service != null && isServiceWorking) {
			service.unregisterFragmentObserver(AuthorizationFragment.this);

			context.unbindService(serviceConnection);
		}
	}

	/**
	 * Used in service to notify fragment that service is about to end his work.
	 * This means that authorizzation process is fully completed.
	 */
	public void notifyServiceCompletion() {
		context.unbindService(serviceConnection);

		isServiceWorking = false;
	}

	/**
	 * Implementation of {@link ServiceConnection} important for establishing
	 * connection to service.
	 */
	private final ServiceConnection serviceConnection = new ServiceConnection() {

		@Override
		public void onServiceDisconnected(final ComponentName name) {
			Log.d(TAG, "service disconnected");

			service = null;
		}

		@Override
		public void onServiceConnected(final ComponentName name,
				final IBinder serviceBinder) {
			service = (AuthorizationServiceBinder) serviceBinder;

			Log.d(TAG, "service connected");

			service.registerFragmentObserver(AuthorizationFragment.this);
		}
	};
}
